package com.ruoyi.common.utils.wechat;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.QrCodeEntity;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信二维码工具类
 *
 * @Author: HuAnze
 * @Date: 2021/2/18 9:47
 */
public class WeChatQrCodeUtils {

    private static Logger log = LoggerFactory.getLogger(WeChatQrCodeUtils.class);

    /**
     * 获取小程序二维码
     */
    public static QrCodeEntity getQrCode(Long id) {
        QrCodeEntity res = new QrCodeEntity();
        try {
            RestTemplate restTemplate = SpringUtils.getBean(RestTemplate.class);

            // 获取access_token
            ResponseEntity<JSONObject> tokenJson = restTemplate.getForEntity(WeChatConstants.getTokenUrl(), JSONObject.class);
            String accessToken = tokenJson.getBody().get("access_token").toString();
            String expiresIn = tokenJson.getBody().get("expires_in").toString();
            // url请求参数值
            Map<String, Object> params = new HashMap<String, Object>(20);
            params.put("scene", id);
            params.put("page", "pages/son/register/register");

            byte[] byteArray = null;
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
            JSONObject jsonObject = new JSONObject(params);
            ResponseEntity<byte[]> entity = restTemplate.postForEntity(url, jsonObject, byte[].class);
            // 图片或错误信息
            byteArray = entity.getBody();
            // 微信返回内容，byte[]转为string
            if (null == byteArray) {
                throw new Exception("小程序二维码调用失败");
            }
            String wxReturnStr = new String(byteArray);
            if (wxReturnStr.contains("errcode")) {
                JSONObject json = JSONObject.parseObject(wxReturnStr);
                res.setCode(json.get("errcode").toString());
                res.setMsg(json.get("errmsg").toString());
            } else {
                res.setCode("200");
                res.setMsg("success");
                res.setBuffer(byteArray);
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("微信小程序码getUnlimited接口调用失败", e);
        }
        return res;
    }
}
